/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.view.css;

import java.util.HashMap;

/**
 *
 * @author Walter L�tgenau
 */
public class PreProcessor {
    HashMap<CommandType, CommandProcessor> commands = new HashMap<CommandType, CommandProcessor>();

    /**
     * Initializes the preprocessor
     * 
     * @param commands
     */
    public void init(Command[] commands) {
        for (Command command : commands)
            this.commands.put(command.getType(), command.getProcessor());
    }

    /**
     * Split the file into tokens and process the tokens.
     *
     * @param userSettings
     * @param input
     * @return
     */
    public String preProcess(HashMap<String, String> userSettings, String input) {
        PreProcessorContext context = new PreProcessorContext(userSettings, input);
        Tokenizer tokenizer = new Tokenizer(input, context.getDefinitions());

        StringBuilder buf = new StringBuilder();
        while (tokenizer.hasNext()) {
            Token token = tokenizer.next();

            CommandProcessor processor = commands.get(token.getType());
            if (processor != null)
                buf.append(processor.process(token, context));
        }
        buf.append(tokenizer.tail());

        return buf.toString();
    }


}
